import React, { useEffect, useState,useCallback  } from 'react'
import { useSearchParams,useNavigate } from 'react-router-dom'
import { SearchBar, Image, List, Ellipsis, InfiniteScroll } from 'antd-mobile'
import axios from 'axios'

import { baseUrl } from '../utils/request'

function Search() {
    const [params, setParams] = useSearchParams();
    const [keyword, setKeyword] = useState(params.get('keyword') || '')
    const [datalist, setDatalist] = useState([])
    const [total, setTotal] = useState(0)
    const search = async (value) => {
        // console.log('value', value)
        setParams(`keyword=${value}`)

        // 发起ajax请求，搜索商品
        getData()
    }
    const changeKeyword = (value) => {
        setKeyword(value)
    }

    const getData = async () => {
        const { data } = await axios.get('http://120.76.247.5:2003/api/search', {
            params: {
                keyword,
                page
            }
            
        })
        // console.log('data', data)

        // 实现滚动加载的功能，每次获取数据后，必须在元数据的基础上增加数据
        const newDatalist = [...datalist, ...data.data.result]
        setDatalist(newDatalist)
        setTotal(data.data.total)

        // 设置是否还有新的数据
        setHasMore(newDatalist.length < data.data.total)

        // 请求结束后loading改为false
        setLoading(false);
    }

    const [page, setPage] = useState(1)
    const [hasMore, setHasMore] = useState(false)
    const [loading,setLoading] = useState(false);
    const loadMore = () => {
        console.log('loadMore',page)
        // 节流：非加载中状态且还有未加载完的数据时才发起请求
        if(hasMore && !loading){
            setPage(page + 1)
            setLoading(true)
        }
    }

    const navigate = useNavigate();
    const gotoDetail = useCallback((id)=>{
        // navigate('/goods?id='+id)
        navigate('/goods/'+id)
    },[])

    useEffect(() => {
        getData();
    }, [page])

    return <div>
        <SearchBar
            value={keyword}
            showCancelButton
            onSearch={search}
            onChange={changeKeyword}
        />
        <List header={`搜索结果: ${total}条记录`}>
            {
                datalist.map(item => (
                    <List.Item key={item._id} prefix={<Image width={60} src={baseUrl + item.img_url} />} onClick={gotoDetail.bind(null,item._id)}>
                        <Ellipsis content={item.goods_name} rows={3} />
                        <p className='price'><del>{item.price}</del><span>{item.sales_price}</span></p>
                    </List.Item>
                ))
            }

        </List>
        <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
    </div>
}

export default Search;